package com.bootdo.system.controller;

import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.system.domain.UserDO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.system.domain.ConfirmImgDO;
import com.bootdo.system.service.ConfirmImgService;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 发货确认单（回执单）图片信息表
 * 
 * @author xm
 * @email 1992lcg@163.com
 * @date 2021-12-27 14:38:09
 */
 
@Controller
@RequestMapping("/system/confirmImg")
public class ConfirmImgController {
    @Autowired
    private ConfirmImgService confirmImgService;

    @Value("${bootdo.uploadPath}")
    private String uploadPath;

    @GetMapping()
    @RequiresPermissions("system:confirmImg:confirmImg")
    String ConfirmImg() {
        return "system/confirmImg/confirmImg";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("system:confirmImg:confirmImg")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        //查询列表数据，物流角色个人查个人导入的信息，药厂的要看到所有
        UserDO user = ShiroUtils.getUser();
        if(user.getUsername().contains("sdyy") || "admin".equals(user.getUsername())){
            params.put("createUser", "");
        }else {
            params.put("createUser", user.getUserId().toString());
        }

        Query query = new Query(params);
        List<ConfirmImgDO> confirmImgList = confirmImgService.list(query);
        int total = confirmImgService.count(query);
        PageUtils pageUtils = new PageUtils(confirmImgList, total);
        return pageUtils;
    }

    @GetMapping("/add")
    @RequiresPermissions("system:confirmImg:add")
    String add() {
        return "system/confirmImg/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("system:confirmImg:edit")
    String edit(@PathVariable("id") String id, Model model) {
        ConfirmImgDO confirmImg = confirmImgService.get(id);
        model.addAttribute("confirmImg", confirmImg);
        return "system/confirmImg/edit";
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("system:confirmImg:add")
    public R save(@RequestParam("imgs[]") MultipartFile[] files) {
        try {
            confirmImgService.save(files);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
        return R.ok();
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("system:confirmImg:edit")
    public R update(ConfirmImgDO confirmImg) {
        confirmImgService.update(confirmImg);
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("system:confirmImg:remove")
    public R remove(String id) {
        if (confirmImgService.remove(id) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("system:confirmImg:batchRemove")
    public R remove(@RequestParam("ids[]") String[] ids) {
        confirmImgService.batchRemove(ids);
        return R.ok();
    }

    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") String id, Model model) {
        ConfirmImgDO confirmImgDO = confirmImgService.get(id);
        model.addAttribute("info", confirmImgDO);
        return "system/confirmImg/detail";
    }

    /**
     * 批量下载图片
     *
     * @param ids
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping("/batchExport")
    public void batchExportImgs(@RequestParam("ids") String[] ids, HttpServletRequest request, HttpServletResponse response) {
        List<ConfirmImgDO> list = confirmImgService.getImgList(ids);
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
            String downloadFilename = "回执单" + sdf.format(new Date()) + ".zip";
            downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");//转换中文否则可能会产生乱码
            response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);// 设置在下载框默认显示的文件名
            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());

            for (ConfirmImgDO confirmImgDO : list) {
                String imgUrl = confirmImgDO.getImgUrl();
                String filePath = uploadPath + imgUrl.substring(7);
                //String fileName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1);
                File file = new File(filePath);
                zos.putNextEntry(new ZipEntry(confirmImgDO.getExpressNo() + imgUrl.substring(imgUrl.lastIndexOf("."))));
                InputStream fis = new FileInputStream(file);
                byte[] buffer = new byte[1024];
                int r = 0;
                while ((r = fis.read(buffer)) != -1) {
                    zos.write(buffer, 0, r);
                }
                fis.close();
            }
            zos.flush();
            zos.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
	

